<template>
  <div id="Po" v-loading="loading">
    <v-tableTitle
      :btnConfig="btnConfig"
      :tableSelectData="tableSelectData"
      :title="$t('in.pokey1')"
      @del="del"
      @exportPo="exportPo"
      @newCreate="newCreate"
      @tallyOrder="tallyOrder"
      @downloadExcelFile="downloadExcelFile"
      @activeOrder="activeOrder"
      @handleDownErrorFile="exceptionFileUrl"
      @handleDownTemplate="downloadExcelFile"
    />
    <v-table
      :pageSize="pageSize"
      :page="page"
      :tableConfig="tableConfig"
      :tableData="tableData"
      :total="total"
      @findData="getTableData"
      @getTableData="getTableData"
      @searhData="searhData"
      @selectData="selectData"
      @setdialog="setdialog"
      @upData="getTableData"
      ref="table"
    ></v-table>
  </div>
</template>

<script type="text/ecmascript-6">
import drawer from "./deawer/Deawer"
import tableTitle from "commons/TableTitle";
import table from "commons/Table";
import baseMixin from "@/mixins/BaseMixin";
import config from "./Config";

export default {
    name: "po",
    mixins: [baseMixin, config],
    data() {
        return {
          // 采购订单
          importType: 10310,
          loading: false,
          tableConfig: [
            {
              label: this.$t('in.pokey'),
              prop: "pokey",
              input: "input",
            },
            {
              label: this.$t('in.storerkey'),
              prop: "storerkey",
              input: "input",
            },
            {
              label: this.$t('common.status'),
              prop: "status",
              input: "select",
              options: this.getOptions("codelkup/POSTATUS")
            },
            {
              label: this.$t('common.type'),
              prop: "potype",
              input: "select",
              options: this.getOptions("codelkup/POTYPE")
            },
            {
              label: this.$t('in.podate'),
              prop: "podate",
              input: "date",
            },
            {
              label: this.$t('config.supplier'),
              prop: "sellername",
              input: "input",
            },
            {
              label: this.$t('in.externpokey'),
              prop: "externpokey",
              input: "input",
            },
            {
              label: this.$t('in.sellersreference'),
              prop: "sellersreference",
              input: "input",
            },
            {
              label: this.$t('in.totalpoqty'),
              prop: "totalpoqty",
              input: "input",
            },
            {
              label: this.$t('in.surplusqty'),
              prop: "surplusqty",
            },
            {
              label: this.$t('in.overageoveridepercent'),
              prop: "overageoveridepercent",
            },
          ],
          tableData: [],
          pageSize: 10,
          page: 1,
          total: 0,
          tableSelectData: [],
          tableSearhData: {},
        };
    },
    computed: {
        btnConfig() {
            return [
              {label: this.$t('common.create'), certigier: this.newStatus||!this.btnPermNameList.includes('WM010401'), invalid: "newCreate"},
              {label: this.$t('common.delete'), certigier: this.deleteStatus||!this.btnPermNameList.includes('WM010402'), disabled: true, invalid: "del"},
              {type: "file", certigier: this.uploadStatus||!this.btnPermNameList.includes('WM010403'), label: this.$t('common.import'), invalid: "file",importType:'10310',importUrl:"importPo",downTemplate:"handleDownTemplate",sheetKey:"poDetailList"},
              // {label: this.$t('config.importTemDownload'), certigier: this.poiStatus||!this.btnPermNameList.includes('WM010404'), invalid: "downloadExcelFile"},
              {label: this.$t('common.export'), certigier: this.downloadStatus||!this.btnPermNameList.includes('WM010405'), disabled: true, invalid: "exportPo"},
              {
                type: "more", label: this.$t('common.moreMenu'), certigier: !this.btnPermNameList.includes('WM010406'),  invalid: "down", btnConfig: [
                  {label: this.$t('in.tallyOrder'), certigier: this.closeStatus||!this.btnPermNameList.includes('WM010407'), disabled: true, invalid: "tallyOrder"},
                  {label: this.$t('in.activeOrder'), certigier: this.activepoStatus||!this.btnPermNameList.includes('WM010408'), disabled: true, invalid: "activeOrder"},
                ]
              }
            ]
        }
    },
    created() {
    },
    methods: {
      exceptionFileUrl(exceptionUrl) {

        console.log("exceptionFileUrl = %o", 1);
        const data = [{
          exceptionFileUrl: exceptionUrl
        }];

        // 异常下载配置
        let urlConf = {responseType: 'blob'};
        let exceptionFileName = "出库订单导入模板异常文件.xls";
        let url = '/comExcelImportResult/downloadExceptionFile';
        let options = {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8'};

        try {
          this.$api.post(url, data, urlConf).then(res => {
            let blobParts = [res.data];
            if (window.navigator.msSaveBlob) {
              const blobObject = new Blob(blobParts);
              window.navigator.msSaveBlob(blobObject, exceptionFileName);
            } else {
              let tagName = 'a';
              const blob = new Blob(blobParts, options);
              const downloadElement = document.createElement(tagName);
              // 创建下载的链接
              const href = window.URL.createObjectURL(blob);
              downloadElement.style.display = 'none';
              downloadElement.href = href;
              // 下载后文件名
              downloadElement.download = exceptionFileName;
              document.body.appendChild(downloadElement);
              // 点击下载
              downloadElement.click();
              // 下载完成移除元素
              document.body.removeChild(downloadElement);
              // 释放掉blob对象
              window.URL.revokeObjectURL(href);
            }
            this.importVisualDialogFlag = false;
            this.initialize();
          });
        } catch (e) {
          this.$message.error(e);
        } finally {
          
        }
      },
      tallyOrder(data) {
        if (data.length > 1) {
          this.$message.error(this.$t('msg.msg32'));
          return;
        }
        if (data[0].status != 11 && data[0].status != 15 && data[0].status != 20) {
          data.forEach(async (item, index) => {
            try {
              let res = await this.$api.get(`/closePoAction/${item.pokey}`);
              
                this.$message.success(res.returnMgr);
                let page = sessionStorage.getItem('page');
                this.getTableData(page, this.tableSearhData);
                this.$refs.table.delSelectData(item, index);
              
            } catch (e) {
              this.$message.error(e);
            }
          });
        } else {
          this.$message.error(this.$t('msg.msg39'));
        }
      },
      async downloadExcelFile(data) {
        try {
          let xlsName = "采购订单导入模板.xls";
          let url = "/downloadExcelFile/" + xlsName;
          let res = await this.$api.post(url, {}, {responseType: 'blob'})
          if (window.navigator.msSaveBlob) {
            var blobObject = new Blob([res.data]);
            window.navigator.msSaveBlob(blobObject, xlsName);
          } else {
            var blob = new Blob([res.data], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8'});
            var downloadElement = document.createElement('a');
            var href = window.URL.createObjectURL(blob); //创建下载的链接
            downloadElement.style.display = 'none';
            downloadElement.href = href;
            downloadElement.download = xlsName; //下载后文件名
            document.body.appendChild(downloadElement);
            downloadElement.click(); //点击下载
            document.body.removeChild(downloadElement); //下载完成移除元素
            window.URL.revokeObjectURL(href); //释放掉blob对象
          }
        } catch (e) {
          this.$message.error(e);
        } finally {
          if (data.length !== 0) {
            
          }
        }
      },

      activeOrder(data) {
        data.forEach(async (item, index) => {
          try {
            let res = await this.$api.get(`/activePoAction/${item.pokey}/${item.status}`);
            
              this.$message.success(res.returnMgr);
              let page = sessionStorage.getItem('page');
              this.getTableData(page, this.tableSearhData);
              this.$refs.table.delSelectData(item, index);
          } catch (e) {
            this.$message.error(e);
          }
        });
      },
      //新建
      async newCreate() {
        try {
          // let res = await this.$api.get('/codeLookup/nCounter/PO');
          // 2022-10-28 修改单号编码取值方式 hkjun
          let numberType = 11701;
          let res = await this.$api.get("/sysNumberRule/getSysNumberByType/"+numberType);
          
            this.$store.commit("setRouteId", res.data.data);
            this.$store.commit("setNewFlag", true);
            this.$router.push({name: 'poDeawer'});
          
        } catch (e) {
          this.$message.error(e);
        }
      },
      //导出
      async exportPo(data) {
        try {
          let res = await this.$api.post('/po/exportPo', data, {responseType: 'blob'})
          if (window.navigator.msSaveBlob) {
            var blobObject = new Blob([res.data]);
            window.navigator.msSaveBlob(blobObject, 'po表.xls');
          } else {
            var blob = new Blob([res.data], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8'});
            var filename = 'po表.xls';
            var downloadElement = document.createElement('a');
            var href = window.URL.createObjectURL(blob); //创建下载的链接
            downloadElement.style.display = 'none';
            downloadElement.href = href;
            downloadElement.download = filename; //下载后文件名
            document.body.appendChild(downloadElement);
            downloadElement.click(); //点击下载
            document.body.removeChild(downloadElement); //下载完成移除元素
            window.URL.revokeObjectURL(href); //释放掉blob对象
          }
        } catch (e) {
          this.$message.error(e);
        }
      },
      //导入
      async upFileBak(data) {
        try {
          let res = await this.$api.post('/po/importPo', data);
            this.$message.success(res.returnMgr);
            let page = sessionStorage.getItem('page');
            this.getTableData(page, this.tableSearhData);
        } catch (e) {
          this.$message.error(e);
        }
      },
      //选中的内容
      selectData(data) {
        this.tableSelectData = data;
      },
      //删除
      async del(data) {
        try {
          let res = await this.$api.post(`/deletePo`, data);
          
            this.$message.success(res.returnMgr);
            let page = sessionStorage.getItem('page');
            this.getTableData(page, this.tableSearhData);
        } catch (e) {
          this.$message.error(e);
        }
      },
      async getTableData(page, data) {
        try {
          this.loading = true;
          let res = await this.$api.post(`/queryListOfPo/${page}`, data);
          
            this.loading = false;
            this.tableData = res.page.list;
            this.page = res.page.curPage;
            this.pageSize = res.page.pageSize;
            this.total = res.page.total;
          
        } catch (e) {
          this.loading = false;
          this.$message.error(e);
        }
      },
      //搜索的值
      searhData(data, up) {
        if (!up) {
          this.tableSearhData = data;
        } else {
          this.tableSearhData = data;
          this.getTableData(1, this.tableSearhData);
        }
      },
      //设置弹框
      setdialog(data) {
        this.$store.commit("setRouteData", data);
        this.$router.push({name: 'poDeawer'});

      },

    },
    mounted() {
        this.$store.commit("setSkip", {});
        this.$store.commit("setRouteId", '');
        this.$store.commit("setNewFlag", false);
        this.$store.commit("setRouteData", {});
        this.$store.commit("setTemporary", "");
        this.getTableData(1, {});
    },
    watch: {
        tableSelectData(data) {
            if (this.permissionStatus) {
                if (data.length > 0) {
                    this.deleteStatus = this.downloadStatus = false;
                    this.closeStatus = this.activepoStatus = false;
                } else {
                    this.deleteStatus = this.downloadStatus = true;
                    this.closeStatus = this.activepoStatus = true;
                }
            }
        }
    },
    components: {
        "v-tableTitle": tableTitle,
        "v-table": table,
        "v-drawer": drawer
    }
};
</script>

<style scoped>
#Po {
  width: 100%;
  height: 99%;
  padding-top: 6px;
}
</style>
